package com.sname.car.common.annotation;

import com.sname.car.bike.service.BikeService;
import com.sname.car.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/**
 * Created By  醉美柳舞之众星捧月
 *
 * @author songx
 * @date 2018/10/18 11:52
 */
public class MyConstraintValidator implements ConstraintValidator<MyConstraint, Object> {

    /**
     * 1： 注解的类;   2: 该注解作用于哪个对象上面,比如String
     * 实现了ConstraintValidator后,不用手动添加Bean或者打其他注解,spring会自动添加扫描
     **/

    private final int LESS_LENGTH = 5;
    private final int MORE_LENGTH = 10;

    /** 可以无限的注入其他的类,来在此处做验证！ */
    @Autowired
    private UserService userService;
    @Autowired
    private BikeService bikeService;

    @Override
    public void initialize(MyConstraint myConstraint) {
        final String message = myConstraint.message();
        System.out.println("开始初始化注解验证！,如果验证失败会抛出错误：  " + message);
    }

    @Override
    public boolean isValid(Object o, ConstraintValidatorContext constraintValidatorContext) {
        /** 此处的Object 是在实体上面打的注解对应的那个实体的值,可以在此处判断! **/
        int nickname = o.toString().trim().length();
        if (StringUtils.isEmpty(o) & (nickname > this.LESS_LENGTH && nickname < this.MORE_LENGTH)) {
            return true;
        }
        return false;
    }
}
